﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Leviathan.Serialize
{
    public class Serializer
    {
        public static string Serialize<T>(T t)
        {
            MemoryStream Stream = new MemoryStream();
            XmlSerializer xml = new XmlSerializer(typeof(T));
            string str = default(string);
            //序列化对象  
            try
            {
                xml.Serialize(Stream, t);
                Stream.Position = 0;
                StreamReader sr = new StreamReader(Stream);
                str = sr.ReadToEnd();
                sr.Dispose();
                Stream.Dispose();
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return str;
        }
        //反序列化
        public static T Deserialize<T>(string xml) where T : class
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(typeof(T));
                    return (T)xmldes.Deserialize(sr);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
